import 'dart:io';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gold/model/review_list_model.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:provider/provider.dart';
import 'package:gold/base/provider_scaffold.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/ui/goods/goods_detail_view_model.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/oval_image.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

/// @description: 商品详情
/// @author tangzhentao
/// @created at 13:37 2024/11/30

class GoodsDetailPage extends StatelessWidget {
  /// 积分商品id
  final int goodsId;

  const GoodsDetailPage({super.key, required this.goodsId});

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: SystemUiOverlayStyle.dark,
      child: ProviderScaffold<GoodsDetailViewmodel>(
          model: GoodsDetailViewmodel(goodsId),
          onInit: (data) => data.firstLoad(),
          builder: (ctx, detail) {
            final goods = detail.detail;
            final imageUrls = goods?.imageUrls?.split(',')?? ['emptyUrl'];
            List<String> tags = [];
            if (goods?.tags?.isNotEmpty == true) {
              tags = goods?.tags?.split(',')?? [];
            }
            return Stack(
              children: [
                Column(
                  children: [
                    Expanded(
                      /// 数据内容
                      child: SmartRefresher(
                        controller: detail.controller,
                        enablePullDown: true,
                        enablePullUp: true,
                        onRefresh: detail.refresh,
                        onLoading: detail.loadMore,
                        child: CustomScrollView(
                          slivers: [
                            /// 轮播图
                            SliverToBoxAdapter(
                              child: SizedBox(
                                width: XfgSize().screenWidth,
                                height: XfgSize().screenWidth,
                                child: Stack(
                                  children: [
                                    CarouselSlider.builder(
                                      options: CarouselOptions(
                                        height: double.infinity, aspectRatio: 1, viewportFraction: 1, autoPlay: true,
                                        onPageChanged: (index, _) => detail.carouselIndex = index,
                                      ),
                                      itemCount: imageUrls.length,
                                      itemBuilder: (_, index, __) => HttpImage(imageUrls[index], size: Size.infinite),
                                    ),
                                    Positioned(
                                      right: XfgSize().size10,
                                      bottom: XfgSize().size15,
                                      child: Container(
                                        width: XfgSize().size40,
                                        height: XfgSize().size18,
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(color: XfgColor.text1D.withValues(alpha: 0.6), borderRadius: BorderRadius.circular(XfgSize().size18)),
                                        child: XfgText('${ctx.select<GoodsDetailViewmodel, int>((k) => k.carouselIndex) + 1}/${imageUrls.length}', fontSize: XfgSize().text14, color: XfgColor.white, height: Platform.isIOS ? 1:null),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                            /// 商品名称
                            SliverToBoxAdapter(
                              child: Container(
                                margin: EdgeInsets.all(XfgSize().size10),
                                alignment: Alignment.centerLeft,
                                child: XfgText(goods?.name?? '', fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.w500),
                              ),
                            ),
                            /// 价格
                            SliverToBoxAdapter(
                              child: Container(
                                  margin: EdgeInsets.only(left: XfgSize().size12),
                                  alignment: Alignment.centerLeft,
                                  child: XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, bold: FontWeight.w500, children: [
                                    TextSpan(text: goods?.price?.toString() ?? '', style: TextStyle(fontSize: XfgSize().text20, fontWeight: FontWeight.bold))
                                  ])
                              ),
                            ),
                            /// 标签
                            SliverToBoxAdapter(
                              child: Visibility(
                                visible: tags.isNotEmpty,
                                child: Container(
                                    margin: EdgeInsets.only(left: XfgSize().size12, top: XfgSize().size8),
                                    alignment: Alignment.centerLeft,
                                    child: Wrap(spacing: XfgSize().size5, runSpacing: XfgSize().size5, children: tags.map((tab) {
                                      final select = tags.indexOf(tab) % 2 == 0;
                                      return Container(
                                        height: XfgSize().size18,
                                        width: XfgSize().size10 + boundingTextSize(tab, style: TextStyle(fontSize: XfgSize().text12)).width,
                                        alignment: Alignment.center,
                                        decoration: select ? BoxDecoration(color: XfgColor.theme, borderRadius: BorderRadius.circular(XfgSize().size2)):BoxDecoration(border: Border.all(color: XfgColor.theme, width: XfgSize().size0_5), borderRadius: BorderRadius.circular(XfgSize().size2)),
                                        child: XfgText(tab, fontSize: XfgSize().text12, color: select ? XfgColor.white:XfgColor.theme),
                                      );
                                    }).toList())
                                ),
                              ),
                            ),
                            /// 黄金
                            SliverToBoxAdapter(
                              child: Visibility(
                                visible: goods?.description?.isNotEmpty == true,
                                child: Container(
                                    margin: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size12, XfgSize().size12, 0),
                                    padding: EdgeInsets.symmetric(horizontal: XfgSize().size12, vertical: XfgSize().size8),
                                    decoration: BoxDecoration(gradient: XfgColor.goodsDetailGoldGradient, borderRadius: BorderRadius.circular(XfgSize().size6)),
                                    child: Row(
                                      children: [
                                        OvalImage(Res.imagesGoodsDetailGold, size: Size(XfgSize().size31, XfgSize().size22)),
                                        SizedBox(width: XfgSize().size8),
                                        Expanded(child: XfgText(goods?.description?? '', fontSize: XfgSize().text14, color: XfgColor.goodsDetailGold))
                                      ],
                                    )
                                ),
                              ),
                            ),
                            /// 比价
                            SliverToBoxAdapter(
                              child: Visibility(
                                visible: detail.peers.isNotEmpty,
                                child:  Container(
                                    margin: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size10, XfgSize().size12, 0),
                                    decoration: white6Decoration,
                                    child: Column(
                                        children: [
                                          Container(
                                            padding: EdgeInsets.only(left: XfgSize().size12, right: XfgSize().size18),
                                            height: XfgSize().size48,
                                            child: Row(
                                              children: [
                                                XfgText('全网比价', fontSize: XfgSize().text20, color: XfgColor.text1, bold: FontWeight.bold),
                                                Expanded(child: XfgText(goods?.updatedAt?? '', fontSize: XfgSize().text14, color: XfgColor.text2, bold: FontWeight.w600, textAlign: TextAlign.end))
                                              ],
                                            ),
                                          ),
                                          ...detail.peers.map((peer) => Container(
                                            height: XfgSize().size44 + XfgSize().size0_5,
                                            decoration: BoxDecoration(border: Border(top: BorderSide(color: XfgColor.colorE, width: XfgSize().size0_5))),
                                            child: Row(
                                              children: [
                                                SizedBox(width: XfgSize().size12),
                                                OvalImage(Res.imagesGoodsDetailGoldIcon, size: Size(XfgSize().size20, XfgSize().size18)),
                                                SizedBox(width: XfgSize().size12),
                                                XfgText(peer.name?? '', fontSize: XfgSize().text14, color: XfgColor.text2),
                                                const Spacer(),
                                                XfgText('￥', fontSize: XfgSize().text12, color: XfgColor.theme, children: [
                                                  TextSpan(text: peer.price?.toStringAsFixed(2)?? '', style: TextStyle(fontSize: XfgSize().text20, fontWeight: FontWeight.bold))
                                                ]),
                                                SizedBox(width: XfgSize().size18),
                                              ],
                                            ),
                                          ))
                                        ]
                                    )
                                ),
                              ),
                            ),
                            /// 评论标题
                            SliverToBoxAdapter(
                              child: Container(
                                  margin: EdgeInsets.fromLTRB(XfgSize().size22, XfgSize().size24, XfgSize().size22, 0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      XfgText('用户评价（${detail.reviewList.length}）', fontSize: XfgSize().text20, color: XfgColor.text1, bold: FontWeight.bold),
                                      XfgText('全部评价 >', fontSize: XfgSize().text14, color: XfgColor.text3)
                                    ],
                                  )
                              ),
                            ),
                            /// 评论
                            _reviewListWidget(detail.reviewList),
                          ],
                        ),
                      ),
                    ),
                    /// 信息
                    Visibility(
                      visible: goods?.descriptionBottom?.isNotEmpty == true,
                      child: Container(
                        decoration: const BoxDecoration(gradient: XfgColor.goodsDetailInfoGradient),
                        height: XfgSize().size34,
                        padding: EdgeInsets.only(left: XfgSize().size26),
                        child: Row(
                          children: [
                            Container(
                              margin: EdgeInsets.only(right: XfgSize().size10),
                              width: XfgSize().size24, height: XfgSize().size24,
                              decoration: const BoxDecoration(gradient: XfgColor.goodsDetailInfoIconGradient, shape: BoxShape.circle),
                              alignment: Alignment.center,
                              child: Icon(Icons.check_sharp, size: XfgSize().size18, color: XfgColor.white),
                            ),
                            XfgText(goods?.descriptionBottom?? '', fontSize: XfgSize().text14, color: XfgColor.text1, bold: FontWeight.w500)
                          ],
                        ),
                      ),
                    ),
                    /// 购买
                    Container(
                      padding: EdgeInsets.only(top: XfgSize().size10, bottom: XfgSize().size10 + XfgSize().bottomBarHeight),
                      alignment: Alignment.center,
                      color: XfgColor.white,
                      child: TextButton(
                        onPressed: detail.buy,
                        style: xfgButtonStyle(Size(XfgSize().size342, XfgSize().size50), radius: XfgSize().size50),
                        child: XfgText('购买', fontSize: XfgSize().text20, color: XfgColor.white, bold: FontWeight.w500),
                      ),
                    ),
                  ],
                ),
                /// 返回
                Positioned(
                  left: XfgSize().size15,
                  top: XfgSize().statusBarHeight,
                  child: GestureDetector(
                    onTap: XfgNav.pop,
                    child: OvalImage(Res.imagesIntegralGoodsBack, size: Size.square(XfgSize().size28)),
                  ),
                ),
              ],
            );
          }
      ),
    );
  }

  /// 评论列表
  Widget _reviewListWidget(List<ReviewModel> list) => SliverList(
    delegate: SliverChildBuilderDelegate((_, index) {
      final isLast = index + 1 == list.length;
      final review = list[index];
      final images = review.images?.isNotEmpty == true ? (review.images?.split(',')?? []):[];
      return Container(
          margin: EdgeInsets.fromLTRB(XfgSize().size14, XfgSize().size12, XfgSize().size14, isLast ? 0:XfgSize().size16),
          decoration: white6Decoration,
          padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size12, XfgSize().size12, XfgSize().size18),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  HttpImage(review.member?.avatar, size: Size.square(XfgSize().size40), radius: BorderRadius.circular(XfgSize().size40)),
                  SizedBox(width: XfgSize().size5),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            XfgText(review.isPrivate == 1 ? '匿名':(review.member?.nickname?? ''), fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.w500),
                            SizedBox(width: XfgSize().size5),
                            OvalImage(Res.imagesGoodReviews, size: Size(XfgSize().size50, XfgSize().size18)),
                          ],
                        ),
                        XfgText('2023.08.12', fontSize: XfgSize().text14, color: XfgColor.text3)
                      ],
                    ),
                  )
                ],
              ),
              Container(
                margin: EdgeInsets.only(top: XfgSize().size20),
                child: XfgText(review.comment?? '', fontSize: XfgSize().text16, color: XfgColor.text1),
              ),
              Visibility(
                visible: images.isNotEmpty,
                child: Container(
                  margin: EdgeInsets.only(top: XfgSize().size20),
                  child: LayoutBuilder(builder: (_, constraint) {
                    final size = (constraint.maxWidth - XfgSize().size24) / 4;
                    return Wrap(
                      spacing: XfgSize().size8, runSpacing: XfgSize().size8,
                      children: images.map((image) => HttpImage(image, size: Size.square(size), radius: BorderRadius.circular(XfgSize().size8))).toList(),
                    );
                  }),
                ),
              )
            ],
          )
      );
    }, childCount: list.length),
  );
}
